ConnectionStringManager.cs
Language: C#
Last Modified: 2020-06-27 1:58:31 PM UTC
File Size: 2821 bytes
Last Modified: 2020-06-27 1:58:31 PM UTC
File Size: 2821 bytes
http://www.penguinstew.ca/example/dataviewer/Model/Connection/ConnectionStringManager.cs
using System;
using System.Configuration;
using System.Data.SqlClient;
namespace Budgeter.Model.Connection
{
public class ConnectionStringManager
{
/// <summary>
/// The server name of the connection
/// </summary>
private string m_serverName;
/// <summary>
/// The database name of the connection
/// </summary>
private string m_databaseName;
/// <summary>
/// Default constructor, loads serverName, databaseName from configs
/// </summary>
public ConnectionStringManager()
{
//Get config settings
m_serverName = ConfigurationManager.AppSettings.Get("ServerName");
m_databaseName = ConfigurationManager.AppSettings.Get("DatabaseName");
}
/// <summary>
/// Constructor taking serverName, databaseName as arguments
/// </summary>
/// <param name="serverName">The name of the SQL server to use</param>
/// <param name="databaseName">The name of the database to use</param>
public ConnectionStringManager(string serverName, string databaseName)
{
m_serverName = serverName;
m_databaseName = databaseName;
}
/// <summary>
/// Uses the SQL connection string builder to get the connection string
/// </summary>
/// <returns>Connection string based off of the set serverName and databaseName</returns>
public string GetConnectionString()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder()
{
DataSource = m_serverName,
InitialCatalog = m_databaseName,
IntegratedSecurity = true
};
return builder.ConnectionString;
}
/// <summary>
/// Tests if the server/database name are non-empty
/// </summary>
/// <returns>True if serverName or DatabaseName are not empty, false otherwise.</returns>
public bool IsInitalized()
{
return !String.IsNullOrEmpty(m_serverName) && !String.IsNullOrEmpty(m_databaseName);
}
/// <summary>
/// Saves the given server/database name to config
/// </summary>
public void SaveSettings()
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings["ServerName"].Value = m_serverName;
configuration.AppSettings.Settings["DatabaseName"].Value = m_databaseName;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79